/*
 * 百度在线网络技术（北京）有限公司拥有本软件版权2021并保留所有权利。
 * Copyright 2021, Baidu.com,Inc 2:Baidu Online Network Technology (Beijing) Co.,Ltd,
 * All rights reserved.
 */

package com.azdebugit.lfu.test;

import org.checkerframework.checker.units.qual.K;

import java.util.HashMap;
import java.util.PriorityQueue;

public class MyLFU extends HashMap {
    public PriorityQueue<Node> queue = new PriorityQueue<Node>();

    protected int maxElements;

    public MyLFU(Integer maxSize) {
        this.maxElements = maxSize;

    }

    public Object put(K k, Object v) {
        //初始值为1
        queue.add(new Node(k, 1));

        if (size() > maxElements) {
            //poll弹出队列头
            remove(queue.poll());

        }

        return super.put(k, v);

    }

    @Override
    public Object get(Object k) {
        for (Node kNode : queue) {
            if (k != null && k.equals(kNode.getKey())) {
                kNode.setCount(kNode.getCount() + 1);

            }

        }

        return super.get(k);

    }

}